App({
  globalData: {
    userInfo: null,
    hasLogin: false,
    baseUrl: 'https://api.example.com', // 替换为你的后端API地址
    rides: [], // 存储顺风车信息
    orders: [], // 存储预约订单信息
  },

  onLaunch: function () {
    // 检查登录状态
    const token = wx.getStorageSync('token');
    if (token) {
      this.globalData.hasLogin = true;
      // 获取用户信息
      this.getUserInfo();
    }

    // 模拟数据 - 在实际应用中应从服务器获取
    this.mockData();
  },

  getUserInfo: function () {
    // 从服务器获取用户信息
    // 实际项目中这里应调用后端API
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.globalData.userInfo = userInfo;
    }
  },

  mockData: function () {
    // 生成模拟数据用于展示
    const rides = [
      {
        id: 1,
        driver: {
          id: 101,
          name: '张三',
          avatar: '/images/avatar1.png',
          phone: '13800138000',
          carInfo: '白色大众朗逸 - 粤B12345',
        },
        startPoint: '科技园',
        endPoint: '市中心',
        date: '2023-05-10',
        time: '08:00',
        seats: 3,
        price: 15,
        remarks: '每天固定路线，准时出发',
      },
      {
        id: 2,
        driver: {
          id: 102,
          name: '李四',
          avatar: '/images/avatar2.png',
          phone: '13900139000',
          carInfo: '黑色本田雅阁 - 粤B54321',
        },
        startPoint: '南山区',
        endPoint: '福田区',
        date: '2023-05-10',
        time: '07:30',
        seats: 4,
        price: 20,
        remarks: '可绕路接送，提前联系',
      },
    ];

    const orders = [
      {
        id: 1,
        rideId: 1,
        status: 'confirmed', // pending, confirmed, completed, cancelled
        passenger: {
          id: 201,
          name: '王五',
          avatar: '/images/avatar3.png',
          phone: '13700137000',
        },
        pickupPoint: '科技园地铁站',
        createdAt: '2023-05-09 14:30',
        seats: 1,
        totalAmount: 15,
      },
    ];

    this.globalData.rides = rides;
    this.globalData.orders = orders;
  },

  // 添加新顺风车信息
  addRide: function (ride) {
    ride.id = this.globalData.rides.length + 1;
    ride.driver = this.globalData.userInfo;
    this.globalData.rides.push(ride);
    return ride;
  },

  // 预约顺风车
  bookRide: function (rideId, bookingInfo) {
    const ride = this.globalData.rides.find((r) => r.id === rideId);
    if (!ride || ride.seats < bookingInfo.seats) {
      return { success: false, message: '座位不足或行程不存在' };
    }

    const order = {
      id: this.globalData.orders.length + 1,
      rideId: rideId,
      status: 'pending',
      passenger: this.globalData.userInfo,
      pickupPoint: bookingInfo.pickupPoint,
      createdAt: new Date().toLocaleString(),
      seats: bookingInfo.seats,
      totalAmount: ride.price * bookingInfo.seats,
    };

    this.globalData.orders.push(order);
    ride.seats -= bookingInfo.seats;

    return { success: true, order: order };
  },
});
